<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>预算总表 - 在线评测系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.sheetjs.com/xlsx-0.20.0/package/dist/xlsx.full.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background-color: #f5f7fa;
            color: #333;
        }

        /* 主要内容样式 */
        .main-content {
            padding: 20px;
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #e8e8e8;
        }

        .page-title {
            font-size: 20px;
            font-weight: 500;
            color: #333;
        }

        .btn-group {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 16px;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            border: none;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .btn-primary {
            background-color: #1890ff;
            color: #fff;
        }

        .btn-primary:hover {
            background-color: #40a9ff;
        }

        .btn-default {
            background-color: #f5f5f5;
            color: #333;
            border: 1px solid #d9d9d9;
        }

        .btn-default:hover {
            background-color: #e8e8e8;
        }

        /* 步骤导航 */
        .steps-container {
            display: flex;
            margin: 30px 0;
            position: relative;
        }

        .steps-container::before {
            content: '';
            position: absolute;
            top: 16px;
            left: 0;
            right: 0;
            height: 2px;
            background-color: #e8e8e8;
            z-index: 1;
        }

        .step {
            flex: 1;
            text-align: center;
            position: relative;
            z-index: 2;
        }

        .step-icon {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: #f5f5f5;
            border: 2px solid #e8e8e8;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 auto 10px;
            font-weight: bold;
            color: #999;
        }

        .step.active .step-icon {
            background-color: #1890ff;
            border-color: #1890ff;
            color: #fff;
        }

        .step.completed .step-icon {
            background-color: #52c41a;
            border-color: #52c41a;
            color: #fff;
        }

        .step-title {
            font-size: 14px;
            color: #999;
            margin-top: 5px;
        }

        .step.active .step-title {
            color: #1890ff;
            font-weight: 500;
        }

        .step.completed .step-title {
            color: #52c41a;
        }

        /* 表单样式 */
        .form-container {
            background-color: #fff;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            padding: 25px;
            margin-bottom: 20px;
        }

        .form-header {
            padding-bottom: 15px;
            margin-bottom: 20px;
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .form-title {
            font-size: 18px;
            font-weight: 500;
            color: #333;
        }

        .form-actions {
            display: flex;
            justify-content: center;
            margin-top: 30px;
            gap: 15px;
        }

        .form-actions .btn {
            min-width: 100px;
        }

        /* 预算总表样式 */
        .budget-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .budget-table th {
            background-color: #f9f9f9;
            text-align: center;
            font-weight: 500;
            white-space: nowrap;
        }
        
        .budget-table td, 
        .budget-table th {
            border: 1px solid #e8e8e8;
            padding: 8px 15px;
        }
        
        .category-row {
            background-color: #f5f7fa;
            font-weight: bold;
        }
        
        .total-row {
            background-color: #f0f5ff;
            font-weight: bold;
        }
        
        .highlight-row {
            background-color: #e6f7ff;
        }
        
        .amount-cell {
            text-align: right;
        }
        
        .budget-input {
            width: 100%;
            text-align: right;
            padding: 5px 8px;
            border: none;
            background-color: transparent;
            border-radius: 0;
            outline: none;
        }

        .budget-input:focus,
        .expense-name-input:focus {
            box-shadow: none;
        }
        
        .category-total, .grand-total {
            width: 100%;
            text-align: right;
            padding: 5px 8px;
            border: none;
            background-color: transparent;
            border-radius: 0;
            font-weight: bold;
        }
        
        .grand-total {
            /* background-color is inherited from .total-row */
            color: #1890ff;
        }

        .not-applicable-checkbox {
            margin-top: 10px;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: #333;
        }
        .btn-add-item, .btn-delete-item {
            background: none;
            border: none;
            cursor: pointer;
            font-size: 24px;
            font-weight: bold;
            line-height: 1;
            padding: 0 8px;
            vertical-align: middle;
        }
        .btn-add-item {
            color: #1890ff;
        }
        .btn-delete-item {
            color: #ff4d4f;
        }
        .budget-table th:last-child,
        .budget-table td:last-child {
            text-align: center;
        }
        .expense-name-input {
            width: 100%;
            border: none;
            border-radius: 0;
            padding: 5px 8px;
            background-color: transparent;
            box-sizing: border-box;
            resize: none;
            overflow: hidden;
            vertical-align: middle;
            font-family: inherit;
            font-size: 14px;
            line-height: 1.5;
            outline: none;
        }
        /* Modal Styles */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: none; /* Hidden by default */
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        .modal-content {
            background-color: #fff;
            padding: 25px;
            border-radius: 8px;
            width: 90%;
            max-width: 1000px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 5px 15px rgba(0,0,0,0.3);
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #e8e8e8;
            padding-bottom: 15px;
            margin-bottom: 20px;
        }
        .modal-header h2 {
            font-size: 18px;
            font-weight: 500;
        }
        .modal-close-btn {
            background: none;
            border: none;
            font-size: 28px;
            cursor: pointer;
            color: #888;
            line-height: 1;
        }
        .preview-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }
        .preview-table th, .preview-table td {
            border: 1px solid #e8e8e8;
            padding: 10px 12px;
            text-align: left;
        }
        .preview-table th {
            background-color: #f9f9f9;
            font-weight: 500;
            text-align: center;
        }
        .preview-table .category-preview-row {
            background-color: #f5f7fa;
            font-weight: bold;
        }
        .preview-table .total-preview-row {
            background-color: #f0f5ff;
            font-weight: bold;
        }
        .preview-table .amount-preview-cell {
            text-align: right;
        }

        /* 隐藏数字输入框的上下箭头 */
        input[type=number]::-webkit-inner-spin-button,
        input[type=number]::-webkit-outer-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }
        input[type=number] {
            -moz-appearance: textfield;
        }
    </style>
</head>
<body>
    <div class="main-content">
        <!-- 步骤导航 -->
        <div class="steps-container">
            <div class="step completed">
                <div class="step-icon">1</div>
                <div class="step-title">基本信息</div>
            </div>
            <div class="step active">
                <div class="step-icon">2</div>
                <div class="step-title">预算总表</div>
            </div>
            <div class="step">
                <div class="step-icon">3</div>
                <div class="step-title">产品购置明细</div>
            </div>
            <div class="step">
                <div class="step-icon">4</div>
                <div class="step-title">软件开发明细</div>
            </div>
            <div class="step">
                <div class="step-icon">5</div>
                <div class="step-title">实施服务明细</div>
            </div>
            <div class="step">
                <div class="step-icon">6</div>
                <div class="step-title">市级政务云租用</div>
            </div>
        </div>

        <!-- 表单 -->
        <div class="form-container">
            <div class="form-header">
                <h2 class="form-title">项目预算总表</h2>
                <div class="btn-group">
                    <button class="btn btn-default" id="previewBtn">
                        <i class="fas fa-eye"></i> 预览
                    </button>
                    <button class="btn btn-default" id="exportBtn">
                        <i class="fas fa-file-export"></i> 导出
                    </button>
                </div>
            </div>

            <form id="budgetForm">
                <table class="budget-table">
                    <thead>
                        <tr>
                            <th style="width: 5%;">序号</th>
                            <th style="width: 62%;">费用名称</th>
                            <th style="width: 25%;">申报额(万元)</th>
                            <th style="width: 8%;">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class="category-row">
                            <td>一</td>
                            <td>硬件类费用</td>
                            <td class="amount-cell"><span class="category-total" name="hardware_total"></span></td>
                            <td><button type="button" class="btn-add-item" data-category="hardware">+</button></td>
                        </tr>
                        <tr data-category="hardware">
                            <td>1</td>
                            <td><textarea class="expense-name-input" rows="1">网络与安全硬件购置费（国产）</textarea></td>
                            <td class="amount-cell"><input type="number" name="hardware_network_domestic" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="hardware">
                            <td>2</td>
                            <td><textarea class="expense-name-input" rows="1">网络与安全硬件购置费（国外）</textarea></td>
                            <td class="amount-cell"><input type="number" name="hardware_network_foreign" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="hardware">
                            <td>3</td>
                            <td><textarea class="expense-name-input" rows="1">服务器与存储设备购置费（国产）</textarea></td>
                            <td class="amount-cell"><input type="number" name="hardware_server_domestic" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="hardware">
                            <td>4</td>
                            <td><textarea class="expense-name-input" rows="1">服务器与存储设备购置费（国外）</textarea></td>
                            <td class="amount-cell"><input type="number" name="hardware_server_foreign" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="hardware">
                            <td>5</td>
                            <td><textarea class="expense-name-input" rows="1">终端设备购置费（国产）</textarea></td>
                            <td class="amount-cell"><input type="number" name="hardware_terminal_domestic" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="hardware">
                            <td>6</td>
                            <td><textarea class="expense-name-input" rows="1">终端设备购置费（国外）</textarea></td>
                            <td class="amount-cell"><input type="number" name="hardware_terminal_foreign" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="hardware">
                            <td>7</td>
                            <td><textarea class="expense-name-input" rows="1">专项设备购置费（国产）</textarea></td>
                            <td class="amount-cell"><input type="number" name="hardware_special_domestic" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="hardware">
                            <td>8</td>
                            <td><textarea class="expense-name-input" rows="1">专项设备购置费（国外）</textarea></td>
                            <td class="amount-cell"><input type="number" name="hardware_special_foreign" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr class="category-row">
                            <td>二</td>
                            <td>软件类费用</td>
                            <td class="amount-cell"><span class="category-total" name="software_total"></span></td>
                            <td><button type="button" class="btn-add-item" data-category="software">+</button></td>
                        </tr>
                        <tr data-category="software">
                            <td>1</td>
                            <td><textarea class="expense-name-input" rows="1">基础软件购置费（国产）</textarea></td>
                            <td class="amount-cell"><input type="number" name="software_basic_domestic" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="software">
                            <td>2</td>
                            <td><textarea class="expense-name-input" rows="1">基础软件购置费（国外）</textarea></td>
                            <td class="amount-cell"><input type="number" name="software_basic_foreign" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="software">
                            <td>3</td>
                            <td><textarea class="expense-name-input" rows="1">应用软件购置费（国产）</textarea></td>
                            <td class="amount-cell"><input type="number" name="software_app_domestic" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="software">
                            <td>4</td>
                            <td><textarea class="expense-name-input" rows="1">应用软件购置费（国外）</textarea></td>
                            <td class="amount-cell"><input type="number" name="software_app_foreign" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr class="highlight-row" data-category="software">
                            <td>5</td>
                            <td><textarea class="expense-name-input" rows="1">应用软件开发费</textarea></td>
                            <td class="amount-cell"><input type="number" name="software_dev" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="software">
                            <td>6</td>
                            <td><textarea class="expense-name-input" rows="1">安全软件及证书购置费</textarea></td>
                            <td class="amount-cell"><input type="number" name="software_security" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr class="category-row">
                            <td>三</td>
                            <td>配套工程类费用</td>
                            <td class="amount-cell"><span class="category-total" name="engineering_total"></span></td>
                            <td><button type="button" class="btn-add-item" data-category="engineering">+</button></td>
                        </tr>
                        <tr data-category="engineering">
                            <td>1</td>
                            <td><textarea class="expense-name-input" rows="1">综合布线费用</textarea></td>
                            <td class="amount-cell"><input type="number" name="engineering_wiring" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="engineering">
                            <td>2</td>
                            <td><textarea class="expense-name-input" rows="1">机房改造工程费用</textarea></td>
                            <td class="amount-cell"><input type="number" name="engineering_room" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="engineering">
                            <td>3</td>
                            <td><textarea class="expense-name-input" rows="1">机房配套设备购置费（国产）</textarea></td>
                            <td class="amount-cell"><input type="number" name="engineering_equipment_domestic" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="engineering">
                            <td>4</td>
                            <td><textarea class="expense-name-input" rows="1">机房配套设备购置费（国外）</textarea></td>
                            <td class="amount-cell"><input type="number" name="engineering_equipment_foreign" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr class="category-row">
                            <td>四</td>
                            <td>相关其他费用</td>
                            <td class="amount-cell"><span class="category-total" name="others_total"></span></td>
                            <td><button type="button" class="btn-add-item" data-category="others">+</button></td>
                        </tr>
                        <tr data-category="others">
                            <td>1</td>
                            <td><textarea class="expense-name-input" rows="1">集成费</textarea></td>
                            <td class="amount-cell"><input type="number" name="others_integration" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="others">
                            <td>2</td>
                            <td><textarea class="expense-name-input" rows="1">软件测评费</textarea></td>
                            <td class="amount-cell"><input type="number" name="others_software_test" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="others">
                            <td>3</td>
                            <td><textarea class="expense-name-input" rows="1">安全测评费</textarea></td>
                            <td class="amount-cell"><input type="number" name="others_security_test" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="others">
                            <td>4</td>
                            <td><textarea class="expense-name-input" rows="1">信息资源建设费</textarea></td>
                            <td class="amount-cell"><input type="number" name="others_resource" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="others">
                            <td>5</td>
                            <td><textarea class="expense-name-input" rows="1">监理费</textarea></td>
                            <td class="amount-cell"><input type="number" name="others_supervision" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="others">
                            <td>6</td>
                            <td><textarea class="expense-name-input" rows="1">政务云租用费</textarea></td>
                            <td class="amount-cell"><input type="number" name="others_cloud" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr data-category="others">
                            <td>7</td>
                            <td><textarea class="expense-name-input" rows="1">其他费用</textarea></td>
                            <td class="amount-cell"><input type="number" name="others_misc" class="budget-input" value="0.00"></td>
                            <td><button type="button" class="btn-delete-item">-</button></td>
                        </tr>
                        <tr class="total-row">
                            <td></td>
                            <td>升级改造费用合计</td>
                            <td class="amount-cell"><input type="text" name="grand_total" readonly class="grand-total"></td>
                            <td></td>
                        </tr>
                    </tbody>
                </table>

                <div class="form-actions">
                    <button type="button" class="btn btn-default" id="prevBtn">
                        <i class="fas fa-arrow-left"></i> 上一步
                    </button>
                    <button type="button" class="btn btn-default" id="saveBtn">
                        <i class="fas fa-save"></i> 保存
                    </button>
                    <button type="button" class="btn btn-primary" id="nextBtn">
                        下一步 <i class="fas fa-arrow-right"></i>
                    </button>
                    <button type="button" class="btn btn-primary" id="submitBtn" disabled>
                        确认提交审核
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div id="previewModal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">
                <h2>项目预算总表预览</h2>
                <button class="modal-close-btn">&times;</button>
            </div>
            <div class="modal-body">
                <!-- Preview table will be injected here by JavaScript -->
            </div>
        </div>
    </div>

    <script>
        // 自定义提示框
        function showCustomAlert(message) {
            // 检查是否已存在提示框
            let alertBox = document.getElementById('customAlertBox');
            
            if (!alertBox) {
                // 创建提示框
                alertBox = document.createElement('div');
                alertBox.id = 'customAlertBox';
                alertBox.style.position = 'fixed';
                alertBox.style.top = '50%';
                alertBox.style.left = '50%';
                alertBox.style.transform = 'translate(-50%, -50%)';
                alertBox.style.backgroundColor = 'white';
                alertBox.style.padding = '20px';
                alertBox.style.borderRadius = '8px';
                alertBox.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
                alertBox.style.zIndex = '2000';
                alertBox.style.minWidth = '300px';
                alertBox.style.textAlign = 'center';
                alertBox.style.animation = 'fadeIn 0.3s';
                
                // 添加动画样式
                const style = document.createElement('style');
                style.textContent = `
                    @keyframes fadeIn {
                        from { opacity: 0; transform: translate(-50%, -60%); }
                        to { opacity: 1; transform: translate(-50%, -50%); }
                    }
                `;
                document.head.appendChild(style);
                
                // 创建遮罩层
                const overlay = document.createElement('div');
                overlay.style.position = 'fixed';
                overlay.style.top = '0';
                overlay.style.left = '0';
                overlay.style.width = '100%';
                overlay.style.height = '100%';
                overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
                overlay.style.zIndex = '1999';
                document.body.appendChild(overlay);
                
                // 不添加标题，直接显示消息
                
                // 创建消息容器
                const messageDiv = document.createElement('div');
                messageDiv.textContent = message;
                messageDiv.style.margin = '15px 0';
                messageDiv.style.fontSize = '16px';
                messageDiv.style.color = '#333';
                alertBox.appendChild(messageDiv);
                
                // 创建确定按钮
                const confirmBtn = document.createElement('button');
                confirmBtn.textContent = '确定';
                confirmBtn.style.backgroundColor = '#4e7bef';
                confirmBtn.style.color = 'white';
                confirmBtn.style.border = 'none';
                confirmBtn.style.padding = '8px 40px';
                confirmBtn.style.borderRadius = '4px';
                confirmBtn.style.fontSize = '14px';
                confirmBtn.style.cursor = 'pointer';
                confirmBtn.style.transition = 'background-color 0.3s';
                
                confirmBtn.onmouseover = function() {
                    this.style.backgroundColor = '#3d6ae8';
                };
                
                confirmBtn.onmouseout = function() {
                    this.style.backgroundColor = '#4e7bef';
                };
                
                confirmBtn.onclick = function() {
                    document.body.removeChild(alertBox);
                    document.body.removeChild(overlay);
                };
                
                alertBox.appendChild(confirmBtn);
                document.body.appendChild(alertBox);
            } else {
                // 更新已存在提示框的消息
                alertBox.querySelector('div:nth-child(1)').textContent = message;
            }
        }
        
        // 验证数量是否为正数
        function validatePositiveNumber(input) {
            const value = parseFloat(input.value);
            // 检查是否为负数
            if (value < 0) {
                showCustomAlert('金额不能为负数！');
                input.value = '0.00'; // 重置为0
                return false;
            }
            return true;
        }
        
        // 预算自动计算功能
        const budgetInputs = document.querySelectorAll('.budget-input');
        budgetInputs.forEach(input => {
            input.addEventListener('input', function() {
                // 验证输入是否为正数
                validatePositiveNumber(this);
                calculateTotals();
            });
        });

        function calculateTotals() {
            let grandTotal = 0;
            const categories = ['hardware', 'software', 'engineering', 'others'];

            categories.forEach(category => {
                const itemRows = document.querySelectorAll(`tr[data-category="${category}"]`);
                let categoryTotal = 0;
                itemRows.forEach(row => {
                    const input = row.querySelector('.budget-input');
                    if (input && input.value) {
                        categoryTotal += parseFloat(input.value);
                    }
                });
                
                const totalSpan = document.querySelector(`span[name="${category}_total"]`);
                if (totalSpan) {
                    totalSpan.textContent = categoryTotal.toFixed(2);
                }
                grandTotal += categoryTotal;
            });

            document.querySelector('input[name="grand_total"]').value = grandTotal.toFixed(2);
        }

        // 初始化计算
        calculateTotals();

        // 动态添加/删除行项目
        document.querySelector('.budget-table tbody').addEventListener('click', function(e) {
            if (e.target.classList.contains('btn-delete-item')) {
                handleDeleteItem(e.target);
            } else if (e.target.classList.contains('btn-add-item')) {
                handleAddItem(e.target);
            }
        });

        document.querySelector('.budget-table tbody').addEventListener('input', function(e) {
            if (e.target.classList.contains('expense-name-input')) {
                autoResizeTextarea(e.target);
            }
        });

        function handleDeleteItem(button) {
            const rowToDelete = button.closest('tr');
            const category = rowToDelete.dataset.category;
            rowToDelete.remove();
            renumberCategoryItems(category);
            calculateTotals();
        }

        function handleAddItem(button) {
            const category = button.dataset.category;
            const categoryRow = button.closest('tr');
            
            const itemRows = document.querySelectorAll(`tr[data-category="${category}"]`);
            const lastItemRow = itemRows.length > 0 ? itemRows[itemRows.length - 1] : categoryRow;

            const newRow = document.createElement('tr');
            newRow.dataset.category = category;
            
            newRow.innerHTML = `
                <td></td>
                <td><textarea class="expense-name-input" rows="1" placeholder="请输入费用名称"></textarea></td>
                <td class="amount-cell"><input type="number" class="budget-input" value="0.00"></td>
                <td><button type="button" class="btn-delete-item">-</button></td>
            `;

            lastItemRow.insertAdjacentElement('afterend', newRow);
            
            // 为新行的预算输入添加验证和计算功能
            const budgetInput = newRow.querySelector('.budget-input');
            budgetInput.addEventListener('input', function() {
                // 验证输入是否为正数
                validatePositiveNumber(this);
                calculateTotals();
            });

            renumberCategoryItems(category);
        }

        function renumberCategoryItems(category) {
            const itemRows = document.querySelectorAll(`tr[data-category="${category}"]`);
            itemRows.forEach((row, index) => {
                row.firstElementChild.textContent = index + 1;
            });
        }

        function autoResizeTextarea(textarea) {
            textarea.style.height = 'auto';
            textarea.style.height = (textarea.scrollHeight) + 'px';
        }

        // Initial resize for all textareas
        document.querySelectorAll('.expense-name-input').forEach(autoResizeTextarea);

        // Preview Modal Logic
        const previewBtn = document.getElementById('previewBtn');
        const modal = document.getElementById('previewModal');
        const closeModalBtn = modal.querySelector('.modal-close-btn');

        previewBtn.addEventListener('click', showPreview);
        closeModalBtn.addEventListener('click', () => modal.style.display = 'none');
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.style.display = 'none';
            }
        });

        function showPreview() {
            const previewTableContainer = modal.querySelector('.modal-body');
            let tableHTML = `<table class="preview-table">
                <thead>
                    <tr>
                        <th style="width: 10%;">序号</th>
                        <th style="width: 65%;">费用名称</th>
                        <th style="width: 25%;">申报额(万元)</th>
                    </tr>
                </thead>
                <tbody>`;

            const sourceRows = document.querySelectorAll('#budgetForm .budget-table tbody > tr');
            
            sourceRows.forEach(row => {
                if (row.classList.contains('category-row')) {
                    const serial = row.cells[0].textContent;
                    const name = row.cells[1].textContent;
                    const total = row.querySelector('.category-total').textContent;
                    tableHTML += `<tr class="category-preview-row">
                                    <td>${serial}</td>
                                    <td>${name}</td>
                                    <td class="amount-preview-cell">${total}</td>
                                 </tr>`;
                } else if (row.classList.contains('total-row')) {
                    const name = row.cells[1].textContent;
                    const total = row.querySelector('input[name="grand_total"]').value;
                    tableHTML += `<tr class="total-preview-row">
                                    <td colspan="2" style="text-align: center;">${name}</td>
                                    <td class="amount-preview-cell">${total}</td>
                                 </tr>`;
                } else if (row.querySelector('.expense-name-input')) { // Item row
                    const serial = row.cells[0].textContent;
                    const nameInput = row.querySelector('.expense-name-input');
                    const name = nameInput ? nameInput.value : row.cells[1].textContent;
                    const amountInput = row.querySelector('.budget-input');
                    const amount = amountInput ? amountInput.value : '';
                    
                    tableHTML += `<tr>
                                    <td style="text-align: center;">${serial}</td>
                                    <td>${name}</td>
                                    <td class="amount-preview-cell">${amount}</td>
                                 </tr>`;
                }
            });

            tableHTML += `</tbody></table>`;
            previewTableContainer.innerHTML = tableHTML;
            modal.style.display = 'flex';
        }

        // Export to Excel Logic
        document.getElementById('exportBtn').addEventListener('click', function() {
            const data = [];
            data.push(["序号", "费用名称", "申报额(万元)"]);

            const sourceRows = document.querySelectorAll('#budgetForm .budget-table tbody > tr');

            sourceRows.forEach(row => {
                if (row.classList.contains('category-row')) {
                    const serial = row.cells[0].textContent;
                    const name = row.cells[1].textContent;
                    const total = row.querySelector('.category-total').textContent;
                    data.push([serial, name, parseFloat(total || 0)]);
                } else if (row.classList.contains('total-row')) {
                    const name = row.cells[1].textContent;
                    const total = row.querySelector('input[name="grand_total"]').value;
                    data.push([]); // Empty row for spacing
                    data.push(['', name, parseFloat(total || 0)]);
                } else if (row.querySelector('.expense-name-input')) {
                    const serial = row.cells[0].textContent;
                    const nameInput = row.querySelector('.expense-name-input');
                    const name = nameInput ? nameInput.value : '';
                    const amountInput = row.querySelector('.budget-input');
                    const amount = amountInput ? parseFloat(amountInput.value || 0) : 0;
                    data.push([parseInt(serial) || serial, name, amount]);
                }
            });

            const worksheet = XLSX.utils.aoa_to_sheet(data);

            worksheet['!cols'] = [{ wch: 8 }, { wch: 60 }, { wch: 20 }];
            
            // Apply number format to the amount column
            for (let i = 1; i < data.length; i++) {
                const cellAddress = 'C' + (i + 1);
                if (worksheet[cellAddress] && worksheet[cellAddress].t === 'n') {
                    worksheet[cellAddress].z = '#,##0.00';
                }
            }

            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, "项目预算总表");
            XLSX.writeFile(workbook, "项目预算总表.xlsx");
        });

        // 检查提交按钮状态
        function checkSubmitButtonStatus() {
            // 从localStorage获取所有页面的完成状态
            const basicInfoCompleted = localStorage.getItem('basicInfoCompleted') === 'true';
            const budgetCompleted = localStorage.getItem('budgetCompleted') === 'true';
            const productCompleted = localStorage.getItem('productCompleted') === 'true';
            const softwareCompleted = localStorage.getItem('softwareCompleted') === 'true';
            const implementationCompleted = localStorage.getItem('implementationCompleted') === 'true';
            const cloudCompleted = localStorage.getItem('cloudCompleted') === 'true';
            
            // 只有当所有页面都完成时，才启用提交按钮
            const allCompleted = basicInfoCompleted && budgetCompleted && productCompleted && 
                                softwareCompleted && implementationCompleted && cloudCompleted;
            
            document.getElementById('submitBtn').disabled = !allCompleted;
            
            if (allCompleted) {
                document.getElementById('submitBtn').style.opacity = '1';
            } else {
                document.getElementById('submitBtn').style.opacity = '0.6';
            }
        }
        
        // 页面加载时检查提交按钮状态
        document.addEventListener('DOMContentLoaded', function() {
            // 检查提交按钮状态
            checkSubmitButtonStatus();
        });
        
        // 保存按钮事件
        document.getElementById('saveBtn').addEventListener('click', function() {
            // 标记当前页面已完成
            localStorage.setItem('budgetCompleted', 'true');
            
            // 检查提交按钮状态
            checkSubmitButtonStatus();
            
            showCustomAlert('预算总表已保存');
        });
        
        // 上一步按钮事件
        document.getElementById('prevBtn').addEventListener('click', function() {
            window.location.href = 'project-basic-info.html';
        });
        
        // 下一步按钮事件
        document.getElementById('nextBtn').addEventListener('click', function() {
            // 标记当前页面已完成
            localStorage.setItem('budgetCompleted', 'true');
            
            // 检查提交按钮状态
            checkSubmitButtonStatus();
            
            window.location.href = 'product-purchase.html';
        });
        
        // 提交按钮功能
        document.getElementById('submitBtn').addEventListener('click', function() {
            if (!this.disabled) {
                showCustomConfirm('确认提交项目申报审核吗？提交后将不能再修改。', function(confirmed) {
                    if (confirmed) {
                        showCustomAlert('项目申报已提交审核，请等待审核结果。');
                        setTimeout(function() {
                            window.location.href = '../project-submit.html';
                        }, 1500);
                    }
                });
            }
        });
    </script>
</body>
</html> 